import React from 'react';
import 'froala-editor/js/froala_editor.pkgd.min';
// Require Editor CSS files.
import 'froala-editor/css/froala_style.min.css';
import 'froala-editor/css/froala_editor.pkgd.min.css';
// Require Font Awesome.
import 'font-awesome/css/font-awesome.css';
import 'froala-editor/js/languages/zh_cn.js';
import FroalaEditor from 'react-froala-wysiwyg';
import OSSWrap from "./OSSWrap";
import CTYPE from "./CTYPE";
import '../../assets/css/common/html-editor.scss'

export default class HtmlEditor extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            model: this.props.content,
            index: this.props.index,
        };
    }

    componentWillReceiveProps(newProps) {
        this.setState({
            index: newProps.index,
            model: newProps.content,
        });
    }

    componentDidMount() {
        $("a").each(function () {
            if ($(this).prop('href').indexOf("https://www.froala.com/wysiwyg-editor") > -1) {
                $(this).parent().css('z-index', '-1');
                $(this).parent().css('height', '0');
                $(this).parent().css('visibility', 'hidden');
                $(this).parent().css('pointer-events', 'none');
                $(this).css('pointer-events', 'none');
                $(this).css('z-index', '-1');
            }
        });
        document.getElementsByClassName('fr-element')[0].style.minHeight = '600px';
    }

    componentDidUpdate() {
        $("a").each(function () {
            if ($(this).prop('href').indexOf("https://www.froala.com/wysiwyg-editor") > -1) {
                $(this).parent().css('z-index', '-1');
                $(this).parent().css('height', '0');
                $(this).parent().css('visibility', 'hidden');
                $(this).parent().css('pointer-events', 'none');
                $(this).css('pointer-events', 'none');
                $(this).css('z-index', '-1');
            }
        });
    }

    imageBeforeUpload = (e, editor, images) => {
        let image = images[0];
        if (!image.name) {
            image.name = Date.parse(new Date()) + '.jpg';
        }
        OSSWrap.upload(CTYPE.namespace.course_img, images[0], {}).then((result) => {
            editor.image.insert(result.url);
            //data-fr-image-pasted

            //处理拷贝图片并上传后临时图片未删除bug
            let dom = document.querySelector("img[data-fr-image-pasted]");
            let parent = dom.parentNode;
            if (parent.childNodes.length === 2) {
                parent.removeChild(parent.childNodes[0]);
            }

        }).catch(function (err) {
            console.log(err);
        });
        return false;
    };


    /*
     * delHtmlTag('<div> <li>1</li> </div>','div')  => '<li>1</li>'
     * delHtmlTag('<div> <li>1</li> </div>',['div','li'])  => '1'
     * */
    delHtmlTag(str, reg) {
        if (reg) {
            if (typeof reg === 'string') {
                let pattern = new RegExp('(<' + reg + '>|</' + reg + '>)', 'g');
                return str.replace(pattern, "");
            }

            if (reg instanceof Array) {
                reg.forEach((item) => {
                    str = this.delHtmlTag(str, item);
                });
                return str;
            }
        }
        return true;//默认
    }

    pasteCleanUp = (e, editor, clipboard_html) => {
        return this.delHtmlTag(clipboard_html, editor.opts.regCleanPaste);
    };

    handleModelChange = (model) => {
        this.props.syncContent(model, this.state.index);
    };

    render() {
        return (
            <div className="html-editor">
                <FroalaEditor
                    config={{
                        language: 'zh_cn',
                        width: '380px',
                        height: '600px',
                        regCleanPaste: ['pre'],//如果只需去除一个标签只传入 'pre' 需要去除多个可以传入 ['pre','article']
                        toolbarButtons: ['undo', 'redo', '|', 'bold', 'fontSize', 'align', 'insertImage'],
                        toolbarButtonsMD: ['undo', 'redo', '|', 'bold', 'fontSize', 'align', 'insertImage'],
                        toolbarButtonsSM: ['undo', 'redo', '|', 'bold', 'fontSize', 'align', 'insertImage'],
                        toolbarButtonsXS: ['undo', 'redo', '|', 'bold', 'fontSize', 'align', 'insertImage'],
                        quickInsertButtons: ['image'],
                        fontSize: ['12', '14', '16', '18', '24', '30', '36'],
                        fontSizeDefaultSelection: '13',
                        fontSizeSelection: true,
                        placeholderText: '',
                        imageUpload: true,
                        imageEditButtons: ['imageAlign', 'imageRemove', 'imageCaption'],
                        events: {
                            'froalaEditor.image.beforeUpload': this.imageBeforeUpload,
                            'froalaEditor.paste.afterCleanup': this.pasteCleanUp,
                        },
                        imageInsertButtons: ['imageUpload',]
                    }}
                    model={this.state.model}
                    onModelChange={this.handleModelChange}
                />
            </div>
        )
    }
}



